package com.open.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.open.bean.AdminUser;
import com.open.component.JwtComponent;
import com.open.result.OpenResult;
import com.open.service.AdminUserService;
import com.open.util.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tanyongpeng
 * <p>des</p>
 **/
@RestController
@RequestMapping("/request/open")
@Slf4j
public class AdminLoginController {

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    JwtComponent jwtComponent;

    @PostMapping("/admin/ht/login")
    public OpenResult login(@RequestBody JSONObject jsonObject, HttpServletRequest request){
        if (StrUtil.isBlank(jsonObject.getStr("username")) || StrUtil.isBlank(jsonObject.getStr("password"))){
            return OpenResult.error("账号或密码为必填项");
        }
        AdminUser adminUser = adminUserService.lambdaQuery()
                .eq(AdminUser::getUsername, jsonObject.getStr("username"))
                .eq(AdminUser::getPassword, jsonObject.getStr("password")).one();

        if (adminUser == null){
            return OpenResult.error("账号或密码错误");
        }else {
            if (adminUser.getUserStatus() == 1){
                return OpenResult.error("账号被禁用");
            }else {
                Map<String,String> map = new HashMap<>();
                map.put("ip", IPUtil.getIpAddress(request));
                map.put("uid",String.valueOf(adminUser.getUid()));
                map.put("t",String.valueOf(new Date().getTime()));
                return OpenResult.success(OpenResult.SUCCESS_CODE,"成功",
                        jwtComponent.generateToken(map));
            }
        }
    }
}
